<template>
  <div>
    <el-drawer v-model="drawer" title="分配班级" @close="closeDrawer" @open="openDrawer" >
      <el-checkbox
        v-model="checkAll"
        :indeterminate="isIndeterminate"
        @change="handleCheckAllChange"
      >
        全选
      </el-checkbox>
      <el-checkbox-group
        v-model="checkedCities"
        @change="handleCheckedCitiesChange"
      >
        <el-checkbox
          v-for="city in classList"
          :key="city._id"
          :value="city._id"
        >
          {{ city.className }}
        </el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-button @click="closeDrawer">取消</el-button>
        <el-button type="primary" @click="addClass" >确定</el-button>
      </template>
    </el-drawer>
  </div>
</template>
<script setup>
import { ref, onMounted , computed , watch } from "vue";
import { getClassListAPI } from "@/api/class";
import { assignClassAPI, getTeacherAndClassAPI } from "@/api/teacher";
import { ElMessage } from "element-plus";
let drawer = defineModel("drawer");
const props = defineProps(['teaId'])
const emits = defineEmits(['getTeacherList'])
let classList = ref([]);
let checkAll = ref(false);
let checkedCities = ref([]);
let isIndeterminate = computed(()=>{
  return checkedCities.value.length > 0 && checkedCities.value.length < classList.value.length;
})
onMounted(() => {
  getClassList();
});
watch(checkedCities,(newVal)=>{
  if(newVal.length === classList.value.length) {
    checkAll.value = true;
  } else {
    checkAll.value = false;
  }
})
//获取班级列表
const getClassList = async () => {
  let result = await getClassListAPI();
  classList.value = result.data.list;
};
const handleCheckAllChange = (val)=>{
  console.log(val);
  checkedCities.value = val ? classList.value.map(item=>item._id) : [];
}
const handleCheckedCitiesChange = ()=>{
  checkAll.value = checkedCities.value.length === classList.value.length;
}
const openDrawer =  ()=>{
  getTeacherAndClass()
}
//获取对应教师带班情况
const getTeacherAndClass = async ()=>{
  let result = await getTeacherAndClassAPI(props.teaId)
  checkedCities.value = result.data.map(item=>item._id)
}
//给教师分配班级
const addClass = async ()=>{
  let result = await assignClassAPI({tId:props.teaId,classArr:checkedCities.value})
  if(result.code == 200) {
    ElMessage.success('分配成功')
    emits('getTeacherList')
    drawer.value = false
  }
}
const closeDrawer = () => {
  drawer.value = false;
};
</script>
<style lang="scss" scoped></style>
